package cn.haut.online_read.controller;

import cn.haut.online_read.enrity.User;
import cn.haut.online_read.mapper.UserMapper;
import cn.haut.online_read.service.UserService;
import cn.haut.online_read.utils.ComputeDigest;
import cn.haut.online_read.utils.Constant;
import cn.haut.online_read.utils.TokenUtils;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;

import static cn.haut.online_read.utils.Constant.*;
import static cn.haut.online_read.utils.ResponseUtils.*;

/**
 * @author xing
 * @date 2021-05-08 0:06
 */
@Controller("userController")
@RequestMapping
@Slf4j
public class UserController {

    private UserMapper userMapper;
    private UserService userService;
    private TokenUtils tokenUtils;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setTokenUtils(TokenUtils tokenUtils) {
        this.tokenUtils = tokenUtils;
    }

    @PostMapping(value = "/login")
    @ResponseBody
    public String loginPost(
            @RequestBody User user
    ) {

        String username = user.getUsername();
        String password = user.getPassword();
        if (username.isBlank() || !username.matches(USERNAME_REGEX)) {
            return createError("提交的用户名格式有误");
        } else if (password.isBlank() || !password.matches(PASSWORD_REGEX)) {
            return createError("提交的密码格式有误");
        }

        // 验证登录
        int validateResult = userService.validateUser(username, password);

        if (validateResult == UserService.VALIDATE_USER_NOT_FOUND) {
            return createError("用户不存在");
        } else if (validateResult == UserService.VALIDATE_USER_NOT_PASS) {
            return createError("密码错误");
        }
        // 获取 Token
        String token = tokenUtils.makeToken(username);

        Map<String, Object> responseMap = new HashMap<>();
        responseMap.put("token", token);
        responseMap.put("permis", validateResult);
        return addSuccess(responseMap);
    }


    @PostMapping(value = "/register")
    @ResponseBody
    public String registerPost(
            @RequestBody User user
    ) {

        String username = user.getUsername();
        String password = user.getPassword();
        if (username.isBlank() || !username.matches(USERNAME_REGEX)) {
            return createError("提交的用户名格式有误");
        } else if (password.isBlank() || !password.matches(PASSWORD_REGEX)) {
            return createError("提交的密码格式有误");
        }

        boolean register = userService.registerUser(username, password);
        if (!register) {
            return createError("用户名已存在");
        }

        return createSuccess();
    }

    /**
     * 用户修改自己密码，或管理员修改用户密码
     *
     * @param map 包含：{
     *                  username 登录的管理员 username
     *                  changeUsername 要修改密码的用户名，如果 username 为空，则也作为登录的用户名
     *                  oldPassword 旧密码
     *                  newPassword 新密码
     *                }
     * @return
     */
    @PostMapping(value = "/changePassword")
    @ResponseBody
    public String changePassword(
            @RequestBody Map<String, String> map,
            @RequestHeader(TOKEN_KEY) String token
    ) {
        // 提取参数
        String username = map.get("username");
        String changeUsername = map.get("changeUsername");
        String oldPassword = map.get("oldPassword");
        String newPassword = map.get("newPassword");

//        log.error("username: {}", username);
//        log.error("token: {}", token);

        // token 验证不通过
        if(token == null || !tokenUtils.validateToken(username, token)) {
            return createTokenError();
        }

        // 要对其他用户操作，但是权限不足
        if(changeUsername != null && userService.getPermissionByName(username) != PERMIS_ADMIN) {
            return createError("你没有该没有权限");
        }

        // 新密码格式不正确
        if(!newPassword.matches(PASSWORD_REGEX)) {
            return createError("提交的密码格式有误");
        }

        // 确定要改密码的用户名
        String changePassUsername = changeUsername == null ? username : changeUsername;

        // changeUsername 为 null , 普通用户修改自己密码
        if(changeUsername == null ){
            // 验证旧密码
            int validateUser = userService.validateUser(changePassUsername, oldPassword);
            // 没找到
            if (validateUser == UserService.VALIDATE_USER_NOT_FOUND) {
                return createError("没找到要修改的用户");
            }
            // 验证失败
            if (validateUser == UserService.VALIDATE_USER_NOT_PASS) {
                return createError("旧密码输入错误");
            }
            // 旧密码正确
        }

        // 设置新密码
        boolean change = userService.changePassword(changePassUsername, newPassword);
        // 修改成功
        if (change) {
            return createSuccess();
        }
        // 修改失败
        else {
            return createError("修改失败");
        }
    }

    @PostMapping(value = "/logout")
    @ResponseBody
    public String logout(
            @RequestBody Map<String, String> requestMap,
            @RequestHeader(TOKEN_KEY) String token
    ) {
        String username = requestMap.get("username");

        // token 验证不通过, 防止别的人恶意下线
        if(token == null || !tokenUtils.validateToken(username, token)) {
            return createTokenError();
        }

        // 删除 token
        Boolean removeToken = tokenUtils.removeToken(username);
        // 删除失败
        if( removeToken == null || !removeToken) {
            // 前端没做处理（觉得没必要），不返回错误了
            return createSuccess();
        }
        return createSuccess();
    }

}
